import { createSlice } from "@reduxjs/toolkit"
import { loginAPI ,getUserInfoAPI} from "@/api/user"
import { getToken,removeToken,setToken as _setToken,getuserName,setuserName,removeuserName } from "@/utils"
import { getUserId,setUserId,removeUserId } from "@/utils/userId"
const userStore = createSlice({
    name:'use',
    //数据状态
    initialState:{
        token:getToken() || '',
        status:'',
        name:'',
        userId:getUserId()||''
    },
    //同步修改方法
    reducers:{
        //登录设置token
        setToken(state,action){
            state.token = action.payload
            state.status = action.payload.status
            console.log("action",action.payload.data.userId)
            state.name=action.payload.data.name
            //并存到本地
            _setToken(action.payload.data.token)
            setuserName(action.payload.data.name)
            setUserId(action.payload.data.userId)
        },
        //获取个人信息
        getUserInfo(state,action){
            state.userInfo =action.payload
        },
        //清除登录信息
        clearUserInfo(state){
            state.token=''
            state.status=''
            removeToken()
            removeuserName()
            removeUserId()
            window.location.reload()
        }
    }
})

//解构actionCreater
const {setToken,clearUserInfo,getUserInfo} = userStore.actions

//获取reducer函数

const useReducer = userStore.reducer

//异步方法封装
//登录
const fetchLogin =(loginForm) =>{
    return async(dispatch)=>{
        //1.发送异步请求
        console.log("ssdd:",loginForm)
        const res = await loginAPI(loginForm)
        console.log("res:",res)
        dispatch(setToken(res))

    }
}
//获取个人信息
const fetchGetUserInfo =() =>{
    return async (dispatch) =>{
    //1.发送异步请求
    const res = await getUserInfoAPI()
    console.log('个人信息',res)
    }
    
    
}

export { fetchLogin ,clearUserInfo,fetchGetUserInfo}

export default useReducer